#!/usr/bin/env python

# Name: 	CUE Reader
# Function:	- Read and parse CUE file

#-------------------------------------------------------------------------

import re

def readTagString(line):
    '''
    readTagString(Str) -> Str

    Read tag string (quoted) from the line.
    '''
    QUOTE = '"'
    start = line.find(QUOTE) + 1
    stop = line[start:].find(QUOTE)
    return line[start : (start + stop)]

#-------------------------------------------------------------------------

class Id3Tags:
    '''
    class Id3Tags - ID3 Tags (read from CUE)

    The following album tags are supported:
        TITLE           - Album Title
        PERFORMER       - performer / artist

    The following track tags are supported:
        TITLE           - Track Title
    '''

    CUE_TITLE_PATTERN     = '[ ]*TITLE'
    CUE_PERFORMER_PATTERN = '[ ]*PERFORMER'
    CUE_TRACK_PATTERN     = '[ ]*TRACK.*AUDIO'
    CUE_STRING_PATTERN    = '.*"[^"]+"'

    def __init__(self):
        self.genre = None
        self.date = None
        self.performer = None
        self.albumTitle = None
        self.tracks = []        # list of tracks ID3 tags

    def readCueFile(self, f_cueFile):
        '''
        Id3Tags Method: readCueFile(File) -> void

        Read CUE file and store tags.
        '''

        # read CUE file
        try:
            cueLines = f_cueFile.readlines()
        except IOError:
            print "WARNING: Error found at reading CUE file %s. Continue without CUE file." % (f_cueFile.name)
            return

        trackFound = False
        for line in cueLines:
            if not re.match(Id3Tags.CUE_TRACK_PATTERN, line) is None:
                trackFound = True

            # read the performer
            if re.match(Id3Tags.CUE_PERFORMER_PATTERN, line) != None and \
               re.match(Id3Tags.CUE_STRING_PATTERN, line) != None and \
               self.performer == None:
                self.performer = readTagString(line)

            # read the title
            elif re.match(Id3Tags.CUE_TITLE_PATTERN, line) != None and \
                 re.match(Id3Tags.CUE_STRING_PATTERN, line) != None:

                if not trackFound and self.albumTitle == None:
                    self.albumTitle = readTagString(line)
                elif trackFound:
                    # add a new track
                    track = Id3TrackTags(readTagString(line))
                    self.tracks.append(track)

    def __getattr__(self, name):
        if name == "numOfTracks":
            return len(self.tracks)
        else:
            print "WARNING: Unknown Tag %s. Ignore it." % (name)
            return None

    def getTrackAttr(self, name, trackNum):
        if trackNum > 0 and trackNum < len(self.tracks):
            return self.tracks[trackNum - 1].__getattr__(name)
        else:
            print "WARNING: Unknown track %s. Ignore it." % (str(trackNum))
            return None

    def printOut(self):
        if not self.genre is None:
            print "Genre:        " + str(self.genre)
        if not self.date is None:
            print "Date:         " + str(self.date)
        if not self.performer is None:
            print "Performer:    " + str(self.performer)
        if not self.albumTitle is None:
            print "Albrum Title: " + str(self.albumTitle)

        print "Tracks:"
        totalNum = len(self.tracks)
        trackNo = 0
        for track in self.tracks:
            trackNo += 1
            #TODO: make the track number print beauty
            print " [%s/%s] %s" % (str(trackNo), str(totalNum), str(track.title))


#-------------------------------------------------------------------------

class Id3TrackTags:
    '''
    class Id3TrackTags - ID3 Track Tags (read from CUE)
    '''

    def __init__(self, title = None):
        self.title = title

    def __getattr__(self, name):
        print "WARNING: Unknown Track Tag %s. Ignore it." % (name)
        return None
